package com.itheima.spring.bestpractive.myinterceptor;

import com.itheima.spring.bestpractive.common.exception.BizEnum;
import com.itheima.spring.bestpractive.common.exception.BizException;
import com.itheima.spring.bestpractive.common.util.JwtUtil;
import com.itheima.spring.bestpractive.pojo.Permission;
import com.itheima.spring.bestpractive.service.PermissionService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
import java.util.logging.Logger;

/**
 * @version 1.0
 * @author: HZY
 * @date: 2025/6/27 15:44
 * @Content: 管理员拦截器
 */
@Component
public class AdminPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token == null){
            System.out.println("没解析到token");
            throw new BizException(BizEnum.TOKEN_MISSING);
        }
        Claims claims = jwtUtil.parseToken(token);
        long roleId = ((Number) claims.get("roleId")).longValue();
        List<Permission> permission = permissionService.getPermission(roleId);
        if(permission.isEmpty()){
            throw new BizException(BizEnum.OPERATION_NOT_ALLOWED);
        }
        Logger logger = Logger.getLogger(AdminPermissionInterceptor.class.getName());
        logger.info("管理员权限：" +  permission.get(0).getPermissionId());
        for (Permission p : permission) {
            if(p.getPermissionId() == 3L){
                return true;
            }
        }
        throw new BizException(BizEnum.USER_PERMISSION_DENIED);
//        return true;
    }
}
